package cn.com.huak.www.sell.service.impl;

import cn.com.huak.www.sell.converter.OrderMaster2OrderDTOConverter;
import cn.com.huak.www.sell.dataObject.OrderDetail;
import cn.com.huak.www.sell.dataObject.OrderMaster;
import cn.com.huak.www.sell.dataObject.ProductInfo;
import cn.com.huak.www.sell.dto.CartDTO;
import cn.com.huak.www.sell.dto.OrderDTO;
import cn.com.huak.www.sell.enums.OrderStatusEnum;
import cn.com.huak.www.sell.enums.PayStatusEnum;
import cn.com.huak.www.sell.enums.ResultEnum;
import cn.com.huak.www.sell.exception.OrderException;
import cn.com.huak.www.sell.repository.OrderDetailRepository;
import cn.com.huak.www.sell.repository.OrderMasterRepository;
import cn.com.huak.www.sell.service.OrderMasterService;
import cn.com.huak.www.sell.service.ProductInfoService;
import cn.com.huak.www.sell.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author huak@wanggang
 * @date 2018/12/31 15:38
 */
@Service
@Slf4j
public class OrderMasterServiceImpl implements OrderMasterService {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @Autowired
    private OrderMasterRepository orderMasterRepository;

    /* 创建订单 */
    @Override
    @Transactional
    public OrderDTO create(OrderDTO orderDTO) {

        /* 订单主表id */
        String orderId = KeyUtil.genKey();

        /* 定义总价格 */
        BigDecimal amount = new BigDecimal(BigInteger.ZERO);

        if(null == orderDTO){
            throw new OrderException(ResultEnum.ORDER_ERROR);
        }

        //1. 查询下单商品(数量 价格)
        List<OrderDetail> orderDetailList = orderDTO.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList){

            //2. 计算总价格
            ProductInfo one = productInfoService.findOne(orderDetail.getProductId());
            if(one == null){
                throw new OrderException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            amount = one.getProductPrice()
                    .multiply(new BigDecimal(orderDetail.getProductQuantity()))
                    .add(amount);

            //3. 订单详情入库
            BeanUtils.copyProperties(one, orderDetail);
            orderDetail.setId(KeyUtil.genKey());
            orderDetail.setOrderId(orderId);

            orderDetailRepository.save(orderDetail);
        }

        //4. 下单
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setId(orderId);
        BeanUtils.copyProperties(orderDTO, orderMaster);
        orderMaster.setOrderAmount(amount);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        orderMasterRepository.save(orderMaster);

        //5. 扣库存
        List<CartDTO> cartDTOS = orderDetailList.stream().map(e -> {
            return new CartDTO(e.getProductId(), e.getProductQuantity());
        }).collect(Collectors.toList());

        productInfoService.decreaseStock(cartDTOS);

        //6. 返回结果
        return orderDTO;
    }

    /* 查询订单详情 */
    @Override
    public OrderDTO findOne(String orderId) {
        /* 订单主表 */
        OrderMaster one = orderMasterRepository.findOne(orderId);
        if(one == null){
            throw new OrderException(ResultEnum.ORDER_NOT_EXIST);
        }

        /* 订单详情表 */
        List<OrderDetail> byOrderId = orderDetailRepository.findByOrderId(one.getId());
        if(null == byOrderId || byOrderId.size() <= 0){
            throw new OrderException(ResultEnum.ORDER_DETAIL_NOT_EXIST);
        }
        // 返回订单详情
        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(one, orderDTO);
        orderDTO.setOrderDetailList(byOrderId);

        return orderDTO;
    }

    /* 查询订单列表 */
    @Override
    public Page<OrderDTO> findList(String buyerOpenid, Pageable pageable) {
        if(buyerOpenid == null || buyerOpenid.length() <= 0){
            throw new OrderException(ResultEnum.OPENID_ERROR);
        }
        //1. 根据当前的openid查询所有的订单列表
        Page<OrderMaster> byBuyerOpenid = orderMasterRepository.findByBuyerOpenid(buyerOpenid, pageable);

        //2. 将所有的订单列表转换成orderDTO列表
        List<OrderDTO> convert = OrderMaster2OrderDTOConverter.convert(byBuyerOpenid.getContent());

        //3. 返回信息
        return new PageImpl<OrderDTO>(convert, pageable, byBuyerOpenid.getTotalElements());
    }

    /* 取消订单 */
    @Override
    @Transactional
    public OrderDTO cancel(OrderDTO orderDTO) {
        if(orderDTO == null){
            throw new OrderException(ResultEnum.ORDER_ERROR);
        }
        OrderMaster one = orderMasterRepository.findOne(orderDTO.getId());
        if(one == null){
            throw new OrderException(ResultEnum.ORDER_NOT_EXIST);
        }
        //1. 判断订单状态
        if(!OrderStatusEnum.NEW.getCode().equals(one.getOrderStatus())){
            log.error("【取消订单】订单状态不正确....");
            throw new OrderException(ResultEnum.ORDER_STATUS_ERROR);
        }

        //2. 修改订单状态
        one.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        BeanUtils.copyProperties(one, orderDTO);
        orderMasterRepository.save(one);

        //3. 返回库存
        if(CollectionUtils.isEmpty(orderDTO.getOrderDetailList())){
            log.error("【取消订单】订单中无商品信息....");
            throw new OrderException(ResultEnum.ORDER_DETAIL_EMPTY);
        }
        List<CartDTO> cartDTOS = orderDTO.getOrderDetailList().stream()
                .map(e -> new CartDTO(e.getProductId(), e.getProductQuantity()))
                .collect(Collectors.toList());
        productInfoService.increaseStock(cartDTOS);
        //4. 已支付的情况退款
        if(PayStatusEnum.success.getCode().equals(one.getPayStatus())){
            // TODO 退款操作

        }

        //5. 返回订单信息
        return orderDTO;
    }

    /* 订单支付 */
    @Override
    @Transactional
    public OrderDTO paid(OrderDTO orderDTO) {
        if(orderDTO == null){
            log.error("【支付订单】订单信息无效....");
            throw new OrderException(ResultEnum.ORDER_ERROR);
        }
        OrderMaster one = orderMasterRepository.findOne(orderDTO.getId());
        if(one == null){
            log.error("【支付订单】订单不存在....");
            throw new OrderException(ResultEnum.ORDER_NOT_EXIST);
        }
        //1. 判断订单状态
        if(!OrderStatusEnum.NEW.getCode().equals(one.getOrderStatus())){
            log.error("【支付订单】订单状态错误....");
            throw new OrderException(ResultEnum.ORDER_STATUS_ERROR);
        }

        //2. 判断支付状态
        if(!PayStatusEnum.WAIT.getCode().equals(one.getPayStatus())){
            log.error("【支付订单】订单支付状态错误....");
            throw new OrderException(ResultEnum.ORDER_PAY_STATUS_ERROR);
        }

        //3. 修改订单支付状态
        one.setPayStatus(PayStatusEnum.success.getCode());
        BeanUtils.copyProperties(one, orderDTO);
        orderMasterRepository.save(one);

        //4. 发起支付
        //TODO 支付

        //5. 返回订单信息
        return orderDTO;
    }

    /* 订单完结 */
    @Override
    @Transactional
    public OrderDTO finish(OrderDTO orderDTO) {
        if(orderDTO == null){
            log.error("【完结订单】订单信息无效....");
            throw new OrderException(ResultEnum.ORDER_ERROR);
        }
        OrderMaster one = orderMasterRepository.findOne(orderDTO.getId());
        if(one == null){
            log.error("【完结订单】订单不存在....");
            throw new OrderException(ResultEnum.ORDER_NOT_EXIST);
        }
        //1. 订单状态判断
        if(!OrderStatusEnum.NEW.getCode().equals(one.getOrderStatus())){
            log.error("【完结订单】订单状态错误....");
            throw new OrderException(ResultEnum.ORDER_STATUS_ERROR);
        }

        //2. 订单状态的修改
        one.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        BeanUtils.copyProperties(one, orderDTO);
        orderMasterRepository.save(one);

        //3. 返回订单信息
        return orderDTO;
    }

    /**
     * 后台订单列表
     * @param pageable
     * @return
     */
    @Override
    public Page<OrderDTO> findList(Pageable pageable) {

        Page<OrderMaster> all = orderMasterRepository.findAll(pageable);

        //2. 将所有的订单列表转换成orderDTO列表
        List<OrderDTO> convert = OrderMaster2OrderDTOConverter.convert(all.getContent());

        //3. 返回信息
        return new PageImpl<OrderDTO>(convert, pageable, all.getTotalElements());
    }
}
